/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package estg.dae.projecto.bank.data;

import estg.dae.projecto.bank.OperationType;
import estg.dae.projecto.bank.model.ElectronicTransfer;
import java.util.Collection;
import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Marco
 */
@Stateless
public class ElectronicTransferDao implements ElectronicTransferDaoLocal {
    @PersistenceContext(unitName="Bank-ejb-PersistenceUnit")
    private EntityManager entityManager;

    public void delete(ElectronicTransfer electronicTransfer) {
        entityManager.remove(electronicTransfer);
        entityManager.flush();
        entityManager.clear();
    }

    public void save(ElectronicTransfer electronicTransfer) {
        entityManager.persist(electronicTransfer);
        entityManager.flush();
        entityManager.clear();
    }

    public Collection<ElectronicTransfer> getAll() {
        return entityManager.createQuery("SELECT e FROM ElectronicTransfer e")
                .getResultList();
    }

    public ElectronicTransfer get(OperationType opType, String originNib, String destinNib, Date date, double value) {
        return (ElectronicTransfer)entityManager.createQuery("SELECT e FROM ElectronicTransfer e " +
                "WHERE e.operationType = ?1 " +
                "AND originNib = ?2" +
                "AND destinNib = ?3" +
                "AND trfValue = ?4" +
                "AND trfDate = ?5")
                .setParameter(1, opType)
                .setParameter(2, originNib)
                .setParameter(3, destinNib)
                .setParameter(4, value)
                .setParameter(5, date)
                .getSingleResult();
    }

    public boolean exists(OperationType opType, String originNib, String destinNib, Date date, double value) {
        Long result = (Long) entityManager.createQuery("SELECT e FROM ElectronicTransfer e " +
                "WHERE e.operationType = ?1 " +
                "AND originNib = ?2" +
                "AND destinNib = ?3" +
                "AND trfValue = ?4" +
                "AND trfDate = ?5")
                .setParameter(1, opType)
                .setParameter(2, originNib)
                .setParameter(3, destinNib)
                .setParameter(4, value)
                .setParameter(5, date)
                .getSingleResult();
        return result.longValue() == 1;
    }
}
